package com.df.excel_export.project_config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ProjectConfigManager {
    private static final ProjectConfigManager ins = new ProjectConfigManager();
    public static ProjectConfigManager getIns(){
        return ins;
    }

    List<ProjectConfig> projectConfigs = new ArrayList<>();
    private String filePath  = "";

    private ProjectConfigManager() {
        filePath = System.getProperty("user.dir")+ File.separator+"data"+File.separator+"configs"+File.separator+"projects.json";
    }

    public void loadFromDisk(){
        projectConfigs.clear();
        File file = new File(filePath);
        if(!file.exists()){
            return;
        }
        if(!file.isFile()){
            return;
        }
        try {
            String s = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
            JSONArray objects = JSON.parseArray(s);
            for (Object object : objects) {
                if(object instanceof JSONObject){
                    JSONObject obj = (JSONObject) object;
                    ProjectConfig javaObject = obj.toJavaObject(ProjectConfig.class);
                    projectConfigs.add(javaObject);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void save2Disk(){
        String jsonString = JSON.toJSONString(projectConfigs, true);
        File file = new File(filePath);
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            Files.writeString(Paths.get(filePath),jsonString);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<ProjectConfig> getCfgs(){
        return projectConfigs;
    }
}
